// my/pages/recipeDetails/recipeDetails.js
Page({
  data: {
    steps: [
      "肥牛卷解冻，用料酒和披萨酱腌制15分钟；",
      "卷饼软化后依次加入肥牛和杂菜，浇上烧烤酱，铺上芝士，卷好卷饼，包上锡纸"
    ],
    comments: [
      {
        id: 1,
        avatar: "/images/avatar.png",
        username: "西瓜",
        time: "11-20",
        content: "哇，看着好好吃的样子~",
        likes: 122,
        isLiked: false
      },
      {
        id: 2,
        avatar: "/images/avatar.png",
        username: "西瓜",
        time: "11-20",
        content: "哇，看着好好吃的样子~",
        likes: 122,
        isLiked: false
      }
    ],
    isPlaying: false,
    currentTime: 0,
    duration: 0,
    currentTimeStr: '00:00',
    durationStr: '00:00',
    playbackRate: 1,
    isMuted: false
  },
  onReady() {
    this.videoCtx = wx.createVideoContext('myVideo', this);
  },

  onEdit(){
    wx.navigateTo({
      url: '/my/pages/recipeVideo/recipeVideo',
    });
  },
  onPlayPause() {
    if (this.data.isPlaying) {
      this.videoCtx.pause();
    } else {
      this.videoCtx.play();
    }
    this.setData({ isPlaying: !this.data.isPlaying });
  },
  onTimeUpdate(e) {
    const current = e.detail.currentTime;
    const duration = this.data.duration || e.detail.duration;
    this.setData({
      currentTime: current,
      currentTimeStr: this.formatTime(current),
      duration: duration,
      durationStr: this.formatTime(duration)
    });
  },
  onLoadedMetaData(e) {
    const duration = e.detail.duration;
    this.setData({
      duration: duration,
      durationStr: this.formatTime(duration)
    });
  },
  formatTime(sec) {
    sec = Math.floor(sec);
    const m = Math.floor(sec / 60).toString().padStart(2, '0');
    const s = (sec % 60).toString().padStart(2, '0');
    return `${m}:${s}`;
  },
  onSpeedChange() {
    const rates = [1, 1.5, 2];
    let idx = rates.indexOf(this.data.playbackRate);
    idx = (idx + 1) % rates.length;
    const newRate = rates[idx];
    this.videoCtx.playbackRate(newRate);
    this.setData({ playbackRate: newRate });
  },
  onMuteToggle() {
    const newMuted = !this.data.isMuted;
    this.videoCtx.mute(newMuted);
    this.setData({ isMuted: newMuted });
  },
  onFullScreen() {
    this.videoCtx.requestFullScreen({ direction: 0 });
  },
  videoError(e) {
    console.error('视频播放错误:', e.detail.errMsg);
    wx.showToast({
      title: '视频加载失败',
      icon: 'none'
    });
  },
  onNavBack() {
    wx.navigateBack();
  },
  onLikeTap(e) {
    const workId = e.currentTarget.dataset.id;
    const newWorksList = this.data.comments.map(item => {
      if (item.id === workId) {
        return {
          ...item,
          isLiked: !item.isLiked,
          likes: item.isLiked ? item.likes - 1 : item.likes + 1
        };
      }
      return item;
    });
    this.setData({ comments: newWorksList });
  }
});